<?php

class UserAction extends Action {

    //验证码
    Public function verify(){
        // 导入Image类库
        import("ORG.Util.Image");
        Image::buildImageVerify(4, 3, 'png', 60, 22, 'verify');
    }


    public function login(){

        //登陆验证
        if (!empty($_POST) && $_POST['login'] == "登录") {
            $username = $_POST["username"];
            $password = md5($_POST["password"]);

            $verify = md5($_POST["verify"]);
            $verify1 = $_SESSION['verify'];

            if ($verify != $verify1) {
                $this->error('验证码错误！');
                exit;
            }

            $user = M('user');
            $condition['username'] = $username;
            $condition['password'] = $password;
            $res = $user->where($condition)->find();

            if ($res) {
                cookie('login', 1);
                cookie('username', $username);

                $this->success('登录成功！', U('Index/index'));
            } else {
                $this->error('登陆失败，请重新登陆！');
            }

        }

        $this->assign();
        $this->display('login');
    }


        //用户退出
    public function logout(){

        cookie('username',null);
        cookie('login',null);
        $this->success('退出成功！');

    }


        //用户注册
    public function register(){

        if (!empty($_POST) && $_POST["dosubmit"] == "注册") {

            $username = $_POST["username"];
            $password = $_POST["password"];

            //数据验证
            $pattern = "/^[a-zA-Z0-9_]{5,15}$/";
            $pregName = preg_match($pattern, $username);
            $pregPwd = preg_match($pattern, $password);

            if (!isset($username) || empty($username)) {
                $this->error('用户名不能为空');
            }
            if ($pregName == 0) {
                $this->error('用户名不合法');
            }


            if (!isset($password) || empty($password)) {
                $this->error('密码不能为空');
            }
            if ($pregPwd == 0) {
                $this->error('密码不合法');
            }

            //将数据插入数据库
            $data['username'] = $username;
            $data['password'] = md5($password);

            $user = M('user');
            $res = $user->data($data)->add();
            if ($res) {
               $this->success('注册成功！', U('User/login'));
            }

        }

        $this->assign();
        $this->display('reg');
    }

}